/*
 * NexradCoverage.java
 *
 * Created on September 30, 2008, 7:56 PM
 */

package msu.ml.tools;

import java.io.*;
import javax.swing.*;
import org.w3c.dom.*;
import msu.ml.util.*;

/**
 *
 * @author  reggie
 */
public class NexradCoverage 
{

	public static void main(String [] args)
	{
		if(args.length < 2)
		{
			System.out.println("Usage: NexradCoverage CALL ANGLE");
			System.out.println("ex: NexradCoverage KMKX 0.5 > xycoverage.csv");
		}

      String callSign = args[0];
      if(callSign == null || callSign.length() == 0)
      {
         System.out.println("Call Sign cannot be empty");
         return;
      }

      String angle = args[1];
      if(angle == null || angle.length() == 0)
      {
         System.out.println("Elevation Angle cannot be empty");
         return;
      }
      
      Document xmlDoc = XmlUtility.parseUri("http://crane.cs.montana.edu/nexrad/index.php/services/site_info/"+callSign);
      String easting = XmlUtility.xPathQuery(xmlDoc, "/site_info/easting").item(0).getTextContent();
      String northing = XmlUtility.xPathQuery(xmlDoc, "/site_info/northing").item(0).getTextContent();
      String height = XmlUtility.xPathQuery(xmlDoc, "/site_info/height").item(0).getTextContent();
      
      int radarX = (int)(Double.parseDouble(easting));
		int radarY = (int)(Double.parseDouble(northing));
		int baseHeight = Integer.parseInt(height);
		double elevationAngle = Double.parseDouble(angle);

		System.out.println("id, easting, northing, height, range, azimuth");
		int id = 0;
		for(int i = 0; i < 360; i++)
		{
			for(int j = 20000; j <= 145000; j += 1000)
			{
				System.out.println(String.format("%1$d, %2$d, %3$d, %4$d, %5$d, %6$d", 
							id++, 
							calcEasting(i, j, radarX), 
							calcNorthing(i,j,radarY),
							calcHeight(j, elevationAngle, baseHeight),
							j, i));
			}
		}
	}

   private static int calcHeight(double range, double angle, double baseHeight)
   {
      double eRad = 8504130;
      return (int)(Math.sqrt(eRad * eRad + range * range + 
            2 * eRad * range * Math.sin(Math.toRadians(angle))) - eRad + baseHeight);
   }
   
   private static int calcEasting(double azimuth, double range, int radarEasting)
   {
      return radarEasting + (int)(range * Math.cos(Math.toRadians(azimuth)));
   }
   
   private static int calcNorthing(double azimuth, double range, int radarNorthing)
   {
      return radarNorthing + (int)(range * Math.sin(Math.toRadians(azimuth)));
   }
   
}
